<template>
  <page-header-wrapper :title="false" >
    <a-card title="员工列表">
      <template #extra>
        <a-tooltip>
          <template #title> 数据导出</template>
          <a-button type="primary" icon="database" @click="handleExpert(queryParam)"></a-button>
        </a-tooltip>
      </template>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="筛选">
                <a-input v-model="queryParam.queryCondition" allow-clear placeholder="请输入" />
              </a-form-item>
            </a-col>
            <!-- <a-col :md="6" :sm="24">
              <a-form-item label="状态">
                <a-select :value="queryParam.status" placeholder="状态">
                  <a-select-option value="1">在职</a-select-option>
                  <a-select-option value="2">离职</a-select-option>
                </a-select>
              </a-form-item>
            </a-col> -->
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" :loading="loading" @click="handleSearch(queryParam)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
                <!-- <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a> -->
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handle()">新增员工</a-button>
        <a-button type="primary" @click="handleGroup()">新增合量</a-button>
        <!-- <a-button type="dashed" @click="tableOption">{{ optionAlertShow && '关闭' || '开启' }} alert</a-button> -->
      </div>
      <a-table
        ref="table"
        size="default"
        :loading="loading"
        rowKey="key"
        :pagination="pagination"
        @change="handleTableChange"
        :columns="columns"
        :data-source="loadData"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="empType" slot-scope="text, record">
          {{ record?.empType == '1' ? '员工' :'合量' }}
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.empStatus == 1">在职</a-tag>
            <a-tag color="#abbac3" v-else>离职</a-tag>
          </template>
        </span>
        <span slot="weChat" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已绑定</a-tag>
            <a-tag color="#abbac3" v-else>未绑定</a-tag>
          </template>
        </span>
        <span slot="dingding" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已绑定</a-tag>
            <a-tag color="#abbac3" v-else>未绑定</a-tag>
          </template>
        </span>
        <span slot="weixin" slot-scope="text, record">
          <template>
            <a-tag color="#82af6f" v-if="record?.status == 1">已绑定</a-tag>
            <a-tag color="#abbac3" v-else>未绑定</a-tag>
          </template>
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a-tag color="#428bca" @click="handleEdit(record)">编辑</a-tag>
          </template>
        </span>
      </a-table>
    </a-card>
    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <create-Group
      ref="groupModal"
      :visible="groupVisible"
      :loading="Loading"
      :model="mdlGroup"
      @cancel="handleGroupCancel"
      @ok="handleGroupOk"
    />
  </page-header-wrapper>
</template>

<script>
import CreateForm from './CreateForm'
import CreateGroup from './createGroup'
import { getEmployeesListUsingPOST ,addEmployeesUsingPOST,exportEmployeeUsingPOST} from  '@/api/api/yuangongguanli.ts'
export default {
  name: 'UserIndex',
  components: {
    CreateForm,
    CreateGroup
  },
  data () {
    return {
      mdl: null,
      groupVisible:false,
      visible: false,
      Loading:false,
      mdlGroup:null,
      confirmLoading:false,
      // 高级搜索 展开/关闭
      advanced: false,
      pagination:{
        total: 0
      },
      // 查询参数
      queryParam: {
        pageNo:1,
        pageSize:10,
        queryCondition:'',
        status:''
      },
      // 表头
      columns: [
        {
          title: '员工工号',
          dataIndex: 'empNo'
        },
        {
          title: '员工姓名',
          dataIndex: 'userName'
        },
        {
          title: '入职日期',
          dataIndex: 'inDate'
        },
        {
          title: '类型',
          dataIndex: 'empType',
          scopedSlots: { customRender: 'empType' }
        },
        {
          title: '员工状态',
          dataIndex: 'empStatus',
          needTotal: true,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '联系电话',
          dataIndex: 'phone'
        },
        {
          title: '归属店',
          dataIndex: 'storeName'
        },
        {
          title: '职务',
          dataIndex: 'jobName'
        },
        {
          title: '绑定微信',
          dataIndex: 'weChat',
          needTotal: true,
          scopedSlots: { customRender: 'weChat' }
        },
        {
          title: '绑定钉钉',
          dataIndex: 'dingding',
          needTotal: true,
          scopedSlots: { customRender: 'dingding' }
        },
        {
          title: '绑定企业微信',
          dataIndex: 'weixin',
          needTotal: true,
          scopedSlots: { customRender: 'weixin' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData:[],
      loading: false,
      optionAlertShow: false
    }
  },
  methods: {
    handleExpert(params){
      exportEmployeeUsingPOST({ ...params}).then((res) => {
          const blob = new Blob([res], {
            type: 'application/vnd.ms-excel;charset=utf-8',
          })
          const filename = '员工列表' + '.xlsx'
          // 将blob对象转为一个URL
          var blobURL = window.URL.createObjectURL(blob)
          // 创建一个a标签
          var tempLink = document.createElement('a')
          // 隐藏a标签
          tempLink.style.display = 'none'
          // 设置a标签的href属性为blob对象转化的URL
          tempLink.href = blobURL
          // 给a标签添加下载属性
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          // 将a标签添加到body当中
          document.body.appendChild(tempLink)
          // 启动下载
          tempLink.click()
          // 下载完毕删除a标签
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
          this.$message.success('导出成功~')
        })  
    },
    handleSearch (params) {
      getEmployeesListUsingPOST(params).then((res) => {
        this.loadData = res.data.list
        this.queryParam.pageNo = this.pagination.current
        this.pagination = { ...this.pagination, total: Number(res.data.total) }
      })
      .catch(() => {
        this.$message.error('获取列表失败,请联系管理员')
      })
    },
    handleTableChange(pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      pager.pageSize = pagination.pageSize
      this.pagination = pager
      this.handleSearch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
        pageNo:pagination.current,
        pageSize:pagination.pageSize,
        queryCondition:this.queryParam.queryCondition,
        status:this.queryParam.status,
        date:this.queryParam.date
      })
    },
    handleGroup(){
      this.groupVisible = true
      this.Loading = false
      const form = this.$refs.groupModal.form
      form.resetFields()
    },
    handle(){
      this.visible = true
      this.confirmLoading = false
      const form = this.$refs.createModal.form
      form.resetFields()
    },
    handleEdit (record) {
      this.$router.push({ path: `/user/user/${record?.id}` })
    },
    handleOk () {
      this.confirmLoading = true
      const form = this.$refs.createModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          const params = {
              ...values,empType:1,inDate:values?.inDate
            }
            addEmployeesUsingPOST({...params}).then((res) => {
              this.handleSearch(this.queryParam)
              this.visible = false
              this.$message.success('操作成功')
            })
            .catch((error) => {
              this.confirmLoading = false
              this.$message.error(((error.response || {}).data || {}).msg || '请求出现错误')
            })
        } else {
         
          this.confirmLoading = false
        }
      })
    },
    handleGroupOk() {
      this.groupVisible = false
      this.Loading = true
      const form = this.$refs.groupModal.form
      form.validateFields((errors, values) => {
        if (!errors) {
          this.$message.warn('开发中')
            // addEmployeesUsingPOST({...values,inDate:values.inDate.format('YYYY-MM-DD HH:mm:ss')}).then((res) => {
            //   this.handleSearch(this.queryParam)
            //   this.$message.success('操作成功')
            // })
            // .catch(() => {
            //   this.$message.error('添加失败,请联系管理员!')
            // })
          
        } else {
          this.Loading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleGroupCancel () {
      this.groupVisible = false
      const form = this.$refs.groupModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
  },
  mounted(){
    this.handleSearch(this.queryParam)
  },
}
</script>